package pl.pollub.medikit.server;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

import pl.pollub.medikit.client.AuthService;
import pl.pollub.medikit.server.db.DBConnectopnHelper;
import pl.pollub.medikit.server.db.dto.User;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class AuthServiceImpl extends RemoteServiceServlet implements
		AuthService {

	private void logg(String msg) {
		System.out.println(msg);
	}
	
	private final static String AUTH_USER_QUERY = "SELECT 'x' FROM %s WHERE PESEL='%s' AND Haslo='%s'";
	
	private final static HashMap<Integer, String> ROLE_TABLE_MAP = new HashMap<Integer, String>() {
		{
			put(User.ROLE_LEKARZ, "Lekarze");
			put(User.ROLE_PRACOWNIK, "Pracownicy");
			put(User.ROLE_PACJENT, "Pacjenci");
		}
	};
	
	@Override
	public boolean validUser(String login, String pssword, int role) {
		Connection dbConnection = DBConnectopnHelper.getDbConnection();
		try {
			if (null != dbConnection) {
				Statement statement = dbConnection.createStatement();
				if (ROLE_TABLE_MAP.containsKey(role)) {
					String tableName = ROLE_TABLE_MAP.get(role);
					String query = String.format(AUTH_USER_QUERY, tableName, login, pssword);
					GWT.log(query);
					logg(query);
					ResultSet users = statement.executeQuery(query);
					System.out.println(users.getRow());
					while (users.next()) {
						logg(users.getString(1));
					}
					if (users.getRow() > 0) {
						return true;
					}
					statement.close();
					dbConnection.close();
				} else {
					GWT.log("Brak tabeli dla roli uzytkownika : "+role);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return false;
	}

}
